import 'package:auto_route/auto_route.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import 'package:provider_student/providers/api_provider.dart';
import '../../providers/auth_provider.dart';
import '../../models/user.dart';

@RoutePage()
class MineTab extends StatelessWidget {
  const MineTab({super.key});

  // GET请求示例 - 获取推荐用户列表
  Future<void> _fetchUserList(BuildContext context) async {
    final apiProvider = Provider.of<ApiProvider>(context, listen: false);

    // 设置访问令牌（实际应用中应从存储服务获取）
    apiProvider.setAccessToken(
      "1925441972349546497_USER&API&17f7741816f3fcd77f37d308c132c3e3a8243eac72688cfeae7d8c208a5c5038",
    );

    final response = await apiProvider.get<List<User>>(
      '/api/v1/data/recommend_user_list',
      queryParameters: {'page': 1},
      fromJson: (data) {
        if (data is List) {
          return data.map((item) => User.fromJson(item)).toList();
        }
        return [];
      },
    );

    if (response.success) {
      debugPrint('获取成功: ${response.data?.length} 个用户');
      // 处理数据...
    } else {
      debugPrint('获取失败: ${response.message}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(middle: Text('我的')),
      child: SafeArea(
        child: Consumer<AuthProvider>(
          builder: (context, auth, child) {
            final user = auth.user;
            if (user == null) {
              return const Center(child: Text('未登录'));
            }

            return ListView(
              padding: const EdgeInsets.all(16),
              children: [
                // 用户头像和基本信息
                Row(
                  children: [
                    Container(
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: CupertinoColors.systemGrey5,
                        image: DecorationImage(
                          image: NetworkImage(user.avatar),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            user.nick,
                            style: const TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            '性别: ${user.sex == 'male' ? '男' : '女'}',
                            style: const TextStyle(
                              color: CupertinoColors.systemGrey,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            '生日: ${DateFormat('yyyy-MM-dd').format(user.birthday)}',
                            style: const TextStyle(
                              color: CupertinoColors.systemGrey,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),

                const SizedBox(height: 32),

                // 设置项列表
                _buildSettingItem(
                  context,
                  icon: CupertinoIcons.person,
                  title: '个人资料',
                  onTap: () {
                    _showNotImplementedAlert(context, '个人资料');
                  },
                ),
                _buildDivider(),

                _buildSettingItem(
                  context,
                  icon: CupertinoIcons.bell,
                  title: '通知设置',
                  onTap: () {
                    _showNotImplementedAlert(context, '通知设置');
                  },
                ),
                _buildDivider(),

                _buildSettingItem(
                  context,
                  icon: CupertinoIcons.lock,
                  title: '隐私设置',
                  onTap: () {
                    _showNotImplementedAlert(context, '隐私设置');
                  },
                ),
                _buildDivider(),

                _buildSettingItem(
                  context,
                  icon: CupertinoIcons.settings,
                  title: '通用设置',
                  onTap: () {
                    _showNotImplementedAlert(context, '通用设置');
                  },
                ),
                _buildDivider(),

                _buildSettingItem(
                  context,
                  icon: CupertinoIcons.info,
                  title: '关于我们',
                  onTap: () {
                    _fetchUserList(context);
                  },
                ),
                _buildDivider(),

                const SizedBox(height: 32),

                // 退出登录按钮
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16.0),
                  child: CupertinoButton(
                    color: CupertinoColors.systemRed,
                    onPressed: () {
                      _showLogoutConfirmation(context, auth);
                    },
                    child: const Text('退出登录'),
                  ),
                ),

                const SizedBox(height: 24),
              ],
            );
          },
        ),
      ),
    );
  }

  // 构建设置项
  Widget _buildSettingItem(
    BuildContext context, {
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
        child: Row(
          children: [
            Icon(icon, color: CupertinoColors.systemBlue),
            const SizedBox(width: 12),
            Expanded(child: Text(title, style: const TextStyle(fontSize: 16))),
            const Icon(
              CupertinoIcons.chevron_right,
              color: CupertinoColors.systemGrey,
              size: 18,
            ),
          ],
        ),
      ),
    );
  }

  // 构建分隔线
  Widget _buildDivider() {
    return const Divider(
      height: 1,
      thickness: 0.5,
      indent: 16,
      endIndent: 16,
      color: CupertinoColors.systemGrey5,
    );
  }

  // 显示未实现功能的提示
  void _showNotImplementedAlert(BuildContext context, String feature) {
    showCupertinoDialog(
      context: context,
      builder:
          (context) => CupertinoAlertDialog(
            title: Text('$feature功能'),
            content: const Text('该功能尚未实现'),
            actions: [
              CupertinoDialogAction(
                isDefaultAction: true,
                onPressed: () => Navigator.pop(context),
                child: const Text('确定'),
              ),
            ],
          ),
    );
  }

  // 显示退出登录确认对话框
  void _showLogoutConfirmation(BuildContext context, AuthProvider auth) {
    showCupertinoDialog(
      context: context,
      builder:
          (context) => CupertinoAlertDialog(
            title: const Text('退出登录'),
            content: const Text('确定要退出当前账号吗？'),
            actions: [
              CupertinoDialogAction(
                isDestructiveAction: true,
                onPressed: () {
                  Navigator.pop(context);
                  auth.logout();
                },
                child: const Text('退出'),
              ),
              CupertinoDialogAction(
                isDefaultAction: true,
                onPressed: () => Navigator.pop(context),
                child: const Text('取消'),
              ),
            ],
          ),
    );
  }
}
